﻿using Microsoft.EntityFrameworkCore;
using SmartAgricultureService.Tables;
using System.Diagnostics;

namespace SmartAgricultureService.Core
{
    public class DatabaseContext(DbContextOptions<DatabaseContext> options) : DbContext(options)
    {
        public DbSet<LogEntry> Logs { get; set; }
        public DbSet<CropEntry> Crop { get; set; }
        public DbSet<AreaEntry> Areas { get; set; }
        public DbSet<ReportEntry> Reports { get; set; }
        public DbSet<DeviceEntry> Devices { get; set; }
        public DbSet<UploadEntry> Uploads { get; set; }
        public DbSet<ReportDetailEntry> ReportDetails { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            if (Debugger.IsAttached)
                optionsBuilder.LogTo(Console.WriteLine);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<LogEntry>(entity =>
            {
                entity.HasOne(o => o.Device)
                    .WithMany(p => p.LogEntries)
                    .HasForeignKey(o => o.DeviceId)
                    .IsRequired(false)
                    .OnDelete(DeleteBehavior.NoAction)
                    .HasConstraintName("log_deviceId");
            });
            modelBuilder.Entity<DeviceEntry>(entity =>
            {
                entity.Property(o => o.Type).HasConversion<int>();
                entity.HasOne(o => o.Area)
                    .WithMany(p => p.Devices)
                    .HasForeignKey(o => o.AreaId)
                    .OnDelete(DeleteBehavior.NoAction)
                    .HasConstraintName("device_areaId");
                entity.HasOne(o => o.Crop)
                    .WithMany(p => p.Devices)
                    .HasForeignKey(o => o.CropId)
                    .OnDelete(DeleteBehavior.NoAction)
                    .HasConstraintName("device_cropId");
            });
            modelBuilder.Entity<UploadEntry>(entity =>
            {
                entity.HasOne(o => o.Device)
                    .WithMany(p => p.UploadEntries)
                    .HasForeignKey(o => o.DeviceId)
                    .OnDelete(DeleteBehavior.NoAction)
                    .HasConstraintName("upload_deviceId");
            });
            modelBuilder.Entity<ReportDetailEntry>(entity =>
            {
                entity.HasOne(o => o.Device)
                    .WithMany(p => p.ReportDetails)
                    .HasForeignKey(o => o.DeviceId)
                    .OnDelete(DeleteBehavior.NoAction)
                    .HasConstraintName("reportDetail_deviceId");
                entity.HasOne(o => o.Report)
                    .WithMany(p => p.ReportDetails)
                    .HasForeignKey(o => o.ReportId)
                    .OnDelete(DeleteBehavior.NoAction)
                    .HasConstraintName("reportDetail_reportId");
            });
        }
    }
}